﻿using Mengsk.ProxyDelivery.Domain;
using Mengsk.ProxyDelivery.Service;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Mengsk.ProxyDelivery.App.UI.Order
{
    /// <summary>
    /// OrderExamineUserControl.xaml 的交互逻辑
    /// </summary>
    public partial class OrderExamineUserControl : UserControl, IPlugin
    {
        private Mengsk.ProxyDelivery.Broadcast.MessageCenter messageCenter = null;
        OrderService orderService = ServiceContainer.GetService<OrderService>();
        OrderGoodsService orderGoodsService = ServiceContainer.GetService<OrderGoodsService>();
        ShoesService shoesService = ServiceContainer.GetService<ShoesService>();
        private object processLock = new object();
        private OrderGoodsVM[] orderGoods = null;

        public string Title
        {
            get { return "偏码审核"; }
        }

        public Control UIControl
        {
            get { return this; }
        }

        public OrderExamineUserControl()
        {
            InitializeComponent();
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                if (this.messageCenter != null)
                {
                    return;
                }
                this.messageCenter = new Broadcast.MessageCenter(3667);
                this.messageCenter.MessageArrived += messageCenter_MessageArrived;
                this.messageCenter.Start();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        void messageCenter_MessageArrived(object sender, Broadcast.MessageArrviedEventArgs e)
        {
            this.Dispatcher.BeginInvoke(new Action(() => messageCenter_MessageArrivedImpl(e)));
        }

        private void messageCenter_MessageArrivedImpl(Broadcast.MessageArrviedEventArgs e)
        {
            try
            {
                lock (this.processLock)
                {
                    if (this.orderGoods == null || this.orderGoods.Length < 1)
                    {
                        return;
                    }
                    var message = e.Message as OrderMoneyChangedMessage;
                    var item = this.orderGoods.FirstOrDefault(obj => obj.Source.Id == message.OrderGoodsId);
                    if (item == null)
                    {
                        return;
                    }
                    item.Price = message.Money;
                    item.CheckComment = message.CheckComment;
                    item.CheckTime = message.CheckTime;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "收到其它人处理的消息，但在更新时失败");
            }
        }

        private void btnDownload_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                this.pbBar.Parameters.Clear();
                this.pbBar.Parameters.Add("checkState", this.cbbCheckState.SelectedIndex - 1);
                this.pbBar.Parameters.Add("startTime", this.dpStart.SelectedDate == null ? DateTime.MinValue : this.dpStart.SelectedDate.Value.Date);
                this.pbBar.Parameters.Add("endTime", this.dpEnd.SelectedDate == null ? DateTime.MinValue : this.dpEnd.SelectedDate.Value.Date.AddDays(10));
                this.pbBar.Parameters.Add("checkComment", this.tbCheckComment.Text.Trim());
                this.pbBar.StartPage();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void Update_Clicked(object sender, EventArgs e)
        {
            try
            {
                lock (this.processLock)
                {
                    TextBlock tb = sender as TextBlock;
                    if (tb == null)
                    {
                        throw new Exception("Edit_Click错误，事件源不是TextBlock");
                    }
                    OrderGoodsVM item = tb.DataContext as OrderGoodsVM;
                    if (item.Price < item.Source.Price)
                    {
                        MessageBox.Show("新价格不能比原始价格低");
                        return;
                    }

                    this.orderService.AddOrderMoney(item.Source.OrderId, item.Source.Id, item.Price);
                    item.CheckTime = DateTime.Now;
                    item.CheckComment = App.LoginOperator.Number + "(" + App.LoginOperator.Name + ")";
                    this.messageCenter.SendMessage(new OrderMoneyChangedMessage(item.Source.Id, DateTime.Now, item.CheckComment, item.Price));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void pbBar_PageChanging(object sender, PageBar.PageChangeEventArgs e)
        {
            var items = this.orderGoodsService.GetNeedCheckOrderGoods(1, e.GetParameter<int>("checkState"), e.GetParameter<DateTime>("startTime"), e.GetParameter<DateTime>("endTime"), e.GetParameter<string>("checkComment"), e.CurrentPage - 1, e.PageSize);
            List<OrderGoodsVM> vms = new List<OrderGoodsVM>();
            foreach (var item in items.Datas)
            {
                Shoes shoes = null;
                try
                {
                    if (item.NumberId > 0)
                        shoes = this.shoesService.GetById(item.NumberId);
                }
                catch
                {
                }
                string url = shoes == null ? "" : shoes.Url;
                vms.Add(new OrderGoodsVM(item, url));
            }
            this.orderGoods = vms.ToArray();
            this.pbBar.Total = items.Total;
            this.pbBar.CurrentCount = items.Datas.Count;
            this.dgItems.ItemsSource = this.orderGoods;
        }


        private void Open_Click(object sender, EventArgs e)
        {
            try
            {
                TextBlock tb = sender as TextBlock;
                if (tb == null)
                {
                    throw new Exception("Edit_Click错误，事件源不是TextBlock");
                }
                OrderGoodsVM item = tb.DataContext as OrderGoodsVM;
                Process.Start(item.Url.Trim());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}
